//
//  CompleteItineratyController.m
//  We_Travel
//
//  Created by lanou3g on 15/12/10.
//  Copyright © 2015年 lanou3g. All rights reserved.
//


#import "CompleteItineratyController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "CityViewCell.h"
#import "BeginDataCell.h"
#import "MapViewController.h"
#import "TravelDayController.h"
#import "RecomendController.h"
#import "EditingViewController.h"
#import "FirstViewController.h"
#import "CoreDataToolHelper.h"
#import "Place.h"
#import "Area.h"
#import "Site.h"
#import "SiteManager.h"

@interface CompleteItineratyController ()<UITableViewDataSource,UITableViewDelegate,BMKMapViewDelegate>
@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *EditButton;
@property (weak, nonatomic) IBOutlet UIButton *orderButton;
@property (nonatomic,strong) NSMutableDictionary *itineratyDictionary;
@property (nonatomic,strong) NSMutableArray *cityArray;

@property (nonatomic,assign) CGFloat cellHeight;

//datePickerView
@property (nonatomic,strong) UIView *pickerView;
@property (nonatomic,strong) NSString *timeStr;


@property (nonatomic,strong) Place *place;
@property (nonatomic,strong) NSArray *areas;
@end


/**
 *  这个界面只是从数据库读取数据,然后展示出来,下面是一个tableView3个分区,中间一个分区有一个row,这个Cell是一个tableView展示每一天的景点
 *
 */
@implementation CompleteItineratyController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    self.place = [[CoreDataToolHelper shareCoreDataTool]fetchPlaceByCount:[SiteManager shareSiteManager].countryCount];
    self.areas = [[CoreDataToolHelper shareCoreDataTool]fetchAreaByCountryCount:[SiteManager shareSiteManager].countryCount];
    self.timeStr = self.place.startTime;
    [self.tableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
}
- (void)dealloc{
    if (_mapView) {
        _mapView = nil;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self setupNavigation];
     self.tableView.bounces = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"CityViewCell" bundle:nil] forCellReuseIdentifier:@"city"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BeginDataCell" bundle:nil] forCellReuseIdentifier:@"begin"];
        // Do any additional setup after loading the view from its nib.
}
//设置navigation
- (void)setupNavigation{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationController.navigationBar.barTintColor = [UIColor cyanColor];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.title = @"完整行程单";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"share.png"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
}
- (void)leftBarButtonItemAction:(UIBarButtonItem *)sender{
    FirstViewController *first = [[FirstViewController alloc]init];
    [self.navigationController pushViewController:first animated:NO];
}
- (void)rightBarButtonItemAction:(UIBarButtonItem *)sender{
 
}
#pragma mark -- mapDelegate
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate{
    MapViewController *mvc = [[MapViewController alloc]init];
    [self.navigationController showViewController:mvc sender:nil];
}
#pragma mark -- tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == self.areas.count + 1){
        return 0;
    }else{
       return 1;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.areas.count + 2;
}
//显示界面Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BeginDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"begin" forIndexPath:indexPath];
   //     self.timeStr = [[CoreDataToolHelper shareCoreDataTool]fetchPlaceByCount:[SiteManager shareSiteManager].countryCount].startTime;
        cell.timeLabel.text = self.timeStr;
        return cell;
    }else{
        CityViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"city"forIndexPath:indexPath];
        cell.arrayData = [NSMutableArray array];
        cell.dayCount = [[self.areas[indexPath.section -1] areaDay]integerValue];
        for (int i = 0; i < [[self.areas[indexPath.section -1] areaDay]integerValue] ; i++) {
            NSArray *array = [NSArray arrayWithArray:[[CoreDataToolHelper shareCoreDataTool]fetchSiteDay:i   AreaCount:indexPath.section - 1 CountryCount:[SiteManager shareSiteManager].countryCount]];
            [cell.arrayData addObject:array];
        }
        [cell.tableView reloadData];
//点击第几天的header响应事件
      [cell setTapBlock:^(NSInteger day){
          [SiteManager shareSiteManager].areaCount = indexPath.section - 1;
          [SiteManager shareSiteManager].areaIDCurrent = [[self.areas[indexPath.section - 1]areaID] integerValue];
          [SiteManager shareSiteManager].areaNameCurrent =[self.areas[indexPath.section - 1]areaName];
          [SiteManager shareSiteManager].dayCountCurrent = day;
          if ([cell.arrayData[day]count] <= 0) {
              RecomendController *rvc = [[RecomendController alloc]init];
              rvc.title = [NSString stringWithFormat:@"%@第%ld天安排推荐",[self.areas[indexPath.section - 1]areaName],day+1];
              rvc.idUrl = [[self.areas[indexPath.section - 1] areaID] integerValue];
              rvc.siteDay = day;
              rvc.areaCount = indexPath.section-1;
              [self.navigationController showViewController:rvc sender:nil];
          }else{
              TravelDayController *tdc = [[TravelDayController alloc]init];
              tdc.title = [NSString stringWithFormat:@"%@第%ld天安排",[self.areas[indexPath.section - 1]areaName],day+1];
              tdc.isRecomend = NO;
              [self.navigationController showViewController:tdc sender:nil];
          }
      }];
//点击景点的响应事件
      [cell setDidSelectBlock:^(NSIndexPath *indexPath1){
          NSLog(@"xuanzeyige cell %ld",indexPath1.row);
      }];
        self.cellHeight = cell.tableView.contentSize.height;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 49;
    }else{
        return self.cellHeight;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
   
    if (section == 0) {
        return self.place.startPlace;
    }else if (section == self.areas.count + 1) {
        return self.place.stopPlace;
    }else{
        return [self.areas[section - 1] areaName];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        [self setupDatePicker];
    }
}
#pragma mark -- datePicker
- (void)setupDatePicker{
    self.tableView.userInteractionEnabled = NO;
    self.mapView.userInteractionEnabled = NO;
    self.pickerView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds)- 300, CGRectGetWidth([UIScreen mainScreen].bounds), 300)];
    self.pickerView.backgroundColor = [UIColor whiteColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 0, 50, 30);
    [button setTitle:@"取消" forState:UIControlStateNormal];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(CGRectGetWidth([UIScreen mainScreen].bounds) - 60, 0, 50, 30);
    [button1 setTitle:@"确定" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.pickerView addSubview:button];
    [self.pickerView addSubview:button1];
    [button addTarget:self action:@selector(cancleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [button1 addTarget:self action:@selector(okayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    UIDatePicker *picker = [[UIDatePicker alloc]initWithFrame:CGRectMake(20, 30, CGRectGetWidth([UIScreen mainScreen].bounds)-40, 200)];
    picker.datePickerMode = UIDatePickerModeDate;
    [self.pickerView addSubview:picker];
    [picker addTarget:self action:@selector(datePickerAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.pickerView];
}
- (void)cancleButtonAction:(UIButton *)sender{
    [self.pickerView removeFromSuperview];
    self.tableView.userInteractionEnabled = YES;
    self.mapView.userInteractionEnabled = YES;
}
- (void)okayButtonAction:(UIButton *)sender{
    [[CoreDataToolHelper shareCoreDataTool]changeStartTime:self.timeStr CountryCount:[SiteManager shareSiteManager].countryCount];
    [self.pickerView removeFromSuperview];
    self.tableView.userInteractionEnabled = YES;
    self.mapView.userInteractionEnabled = YES;
}
- (void)datePickerAction:(UIDatePicker *)sender{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd"];
    self.timeStr = [df stringFromDate:sender.date];
    [self.tableView reloadData];
}


#pragma mark --- bottomTool

- (IBAction)editItineratyButton:(UIButton *)sender {
    EditingViewController *edvc = [[EditingViewController alloc]init];
    [self.navigationController showViewController:edvc sender:nil];
}
- (IBAction)orderButton:(UIButton *)sender {
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
